#!/usr/bin/python3
import os
import sys

# header_path = "/usr/src/linux-headers-5.4.0-65/include/linux/syscalls.h"
file_name = "syscall_hook_proto.h"

def split(str) -> str:
    call = str.split("_", 1)
    return "(*sys_" + call[1] + "_func_t)"

def transform(line):
    pos_start = line.find("sys_")
    pos_end = line.find("(")
    tmp = split(str(line[pos_start:pos_end]))
    if tmp != "":
        tmp = line.replace(str(line[pos_start:pos_end]), tmp)
        return "typedef "+tmp
    return ""

def process_line(line, f):

    if line.startswith("asmlinkage long"):
        tmp = transform(line)
        if tmp != "":
            f.write(tmp)
            return
    f.write(line)

if __name__ == "__main__":

    if len(sys.argv) != 2:
        print("please input syscalls.h path.\n example:/usr/src/linux-headers-<version>/include/linux/syscalls.h\n")
        exit(-1)

    pwd_dir = os.path.dirname(os.path.abspath(__file__))
    test_file = os.path.join(pwd_dir, file_name)

    header_path = sys.argv[1]

    if not os.path.exists(header_path):
        print(header_path, "not exit.")
        exit(1)
    if not os.path.exists(test_file):
        os.mknod(test_file)

    print("from ", header_path)
    print("to ", test_file)

    test_h = open(test_file, "w")
    start = 0
    if not test_h.writable():
        print(test_h.name(), "not writable\n")

    test_h.write("#ifndef _HOOK_SYSCALL_INTERNAL_PROTO_H\n")
    test_h.write("#define _HOOK_SYSCALL_INTERNAL_PROTO_H\n\n")
    test_h.write("#include <linux/syscalls.h>\n\n")

    with open(header_path) as f:
        for line in f:
            if line.startswith("#ifndef CONFIG_ARCH_HAS_SYSCALL_WRAPPER") and start == 0:
                start = 1
                continue
            if line.startswith("#endif /* CONFIG_ARCH_HAS_SYSCALL_WRAPPER */") and start == 1:
                start = 0
            if start == 1:
                process_line(line, test_h)

    test_h.write("#endif /* _HOOK_SYSCALL_INTERNAL_PROTO_H */\n")
    test_h.close()
    print("transform finished ... ...")
